const { read_file, write_file } = require("../common");

function getHero(req) {
  const { q, role, page = 1, pagesize = 10 } = req.query;
  let data = read_file("hero.json").reverse();

  if (q) {
    data = data.filter(
      (item) => item.name == req.query.q || item.title == req.query.q
    );
  }

  if (role) {
    data = data.filter((item) => item.roles.includes(role));
  }
  const total = data.length;

  data = data.slice(page * pagesize - pagesize, pagesize * page);

  return {
    data,
    total,
    page: Number(page),
    pagesize: Number(pagesize),
  };
}

function getHeroRole(req) {
  let data = read_file("hero.json");
  let roles = [];
  data.forEach((item) => {
    roles.push(...item.roles);
  });

  return {
    roles: [...new Set(roles)],
  };
}

function createHero(form){
    let data = read_file("hero.json");
    end_data = data[data.length-1]
    heroId = String(Number(end_data.heroId) + 1)
    form.heroId = heroId
    data.push(form)
    data = JSON.stringify(data)
    write_file("hero.json", data)
}

function updateHero(form, heroId){
  let data = read_file("hero.json");
  data.forEach(item => {
    if(item.heroId == heroId){
      for(key in form){
        item[key] = form[key]
      }
    }
  })
  data = JSON.stringify(data)
  write_file("hero.json", data)
}

function delHero(heroId){
  let data = read_file("hero.json");

  data = data.filter(item => item.heroId != String(heroId))

  data = JSON.stringify(data)
  write_file("hero.json", data)
}

module.exports = {
  getHero,
  getHeroRole,
  createHero,
  updateHero,
  delHero
};
